<template>
  <div class='m-lesson_scheduleDetail'>
    <el-form class="m-lesson_scheduleDetail_form" ref='form' label-width="120px" :model="form" :rules='rules'>
      <el-form-item label='课程：' prop='lesson'>
        <a-select
          v-model='form.lesson'
          :options='lessonData'
        />
      </el-form-item>
      <el-form-item label='班级：' prop='classes'>
        <a-select
          v-model='form.classes'
          :options='classesData'
        />
      </el-form-item>
      <el-form-item label='教室：' prop='classroom'>
        <a-select
          v-model='form.classroom'
          :options='classroomData'
        />
      </el-form-item>
      <el-form-item label='显示颜色：' prop='color'>
        <el-color-picker v-model="form.color"></el-color-picker>
      </el-form-item>
      <el-form-item label='主讲老师：' prop='mainTeacherData'>
        <ul class="list">
          <li
            v-for='(v, i) in form.mainTeacherData'
            :key='v.id'
          >
            <span>{{ v.short_name || v.name }}</span><i class='el-icon-close' @click='deleteMainTeacher(i)'></i>
          </li>
          <li @click='showDialog("mainTeacher")'><i class='el-icon-plus'></i></li>
        </ul>
      </el-form-item>
      <el-form-item label='助教老师：' prop='twoTeacherData'>
        <ul class="list">
          <li
            v-for='(v, i) in form.twoTeacherData'
            :key='v.id'
          >
            <span>{{ v.name }}</span><i class='el-icon-close' @click='deleteTwoTeacher(i)'></i>
          </li>
          <li @click='showDialog("twoTeacher")'><i class='el-icon-plus'></i></li>
        </ul>
      </el-form-item>
      <el-form-item label="上课时间：" prop='time'>
        <el-date-picker
          v-model="form.date"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
        <!-- <div v-else>
          {{ form.date | formatTime }}
        </div> -->
        <a-select
          style='padding-top: 10px;'
          placeholder='选择时间'
          v-model='form.time'
          :options='timeData'
        />
        <!-- <div v-else>{{ timeValue }}</div> -->
      </el-form-item>
      <el-form-item label="备注：" prop='memo'>
        <el-input type="textarea" :rows='5' placeholder="请重新输入备注" v-model.trim="form.memo"></el-input>
      </el-form-item>
      <el-form-item align='right'>
        <el-button type="primary" @click="create">保存</el-button>
        <el-button type="primary" v-if='!isAdd' @click="cancel">删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 选择 dialog -->
    <select-list ref='mainTeacher' @getData='getStudent' title='选择主讲老师' listPath='firmGetStaffs' />
    <select-list ref='twoTeacher' @getData='getTeacher' title='选择助教老师' listPath='firmGetStaffs' />
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import selectList from '@/module/lesson/components/selectList'

export default {
  name: 'm-lesson_schedule_add',

  components: {
    selectList
  },

  data() {
    const validateMain = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请选择主讲教师'))
      } else {
        callback()
      }
    }
    const validateTwo = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请选择助教教师'))
      } else {
        callback()
      }
    }
    return {
      data: [],
      ifRequesting: false,
      selectId: '',
      form: {
        lesson: '',
        classes: '',
        classroom: '',
        date: '',
        time: '',
        color: '',
        memo: '',
        twoTeacherData: [],
        mainTeacherData: []
      },
      rules: {
        lesson: [
          { required: true, message: '请选择课程', trigger: 'blur' }
        ],
        classes: [
          { required: true, message: '请选择班级', trigger: 'blur' }
        ],
        classroom: [
          { required: true, message: '请选择教室', trigger: 'blur' }
        ],
        // date: [
        //   { required: true, message: '请选择日期', trigger: 'blur' }
        // ],
        // time: [
        //   { required: true, message: '请选择时间', trigger: 'blur' }
        // ],
        color: [
          { required: true, message: '请选择颜色', trigger: 'blur' }
        ],
        twoTeacherData: [
          { required: true, validator: validateTwo, trigger: 'blur' }
        ],
        mainTeacherData: [
          { required: true, validator: validateMain, trigger: 'blur' }
        ]
      },
      isAdd: true,
      dialogVisible: false,
      // 下拉列表
      lessonData: [],
      teacherData: [],
      classroomData: [],
      classesData: [],
      timeData: [],
      timeValue: '',
      isHaveDateData: false,
      isHaveTimeData: false
    }
  },

  async mounted() {
    this.getLesson()
    this.getClassroom()
    await this.getClasses()
    this.getTime()
    const { id } = this.$route.query
    if (!id) return false
    this.selectId = id
    this.isAdd = false
    this.getDetail(id)
  },

  methods: {
    getTimeData() {
      const value = this.form.time
      const obj = this.timeData.filter(item => item.value === value)[0]
      this.timeValue = obj ? obj.label : '暂无'
    },

    ...mapMutations(['setTabRoutes']),

    routerPush(type, args) {
      // push 到缓存里
      this.setTabRoutes({ type: 'add', obj: { ...this.getRouterInfoAccordingName(type), ...args } })
    },

    getTeacher(data) {
      this.form.twoTeacherData = data
    },

    getStudent(data) {
      this.form.mainTeacherData = data
    },

    deleteMainTeacher(i) {
      this.$refs.mainTeacher.deleteObj(i)
    },

    deleteTwoTeacher(i) {
      this.$refs.twoTeacher.deleteObj(i)
    },

    showDialog(type) {
      this.$refs[type].show()
    },

    async getDetail(id) {
      const { code, data } = await this.$api.courseGetScheduleInfo({ aId: id })
      if (code === 0) {
        const { class_id, color, course_id, date, room_id, teachers, time_id, memo = '' } = data
        this.form.lesson = course_id
        this.form.classes = class_id
        this.form.classroom = room_id
        this.form.color = color
        this.form.time = time_id
        this.form.date = new Date(parseInt(date + '000', 10))
        this.form.memo = memo
        const mainTeacher = teachers.filter(v => v.type === '2')
        const twoTeacher = teachers.filter(v => v.type === '1')
        this.form.mainTeacherData = mainTeacher
        this.form.twoTeacherData = twoTeacher
        this.$refs.twoTeacher.setData(twoTeacher)
        this.$refs.mainTeacher.setData(mainTeacher)
        this.isHaveDateData = !!date
        this.isHaveTimeData = !!time_id
        // this.getTimeData()
      }
    },

    createParam() {
      const { lesson, classes, classroom, color, time, date, memo, mainTeacherData, twoTeacherData } = this.form
      console.log(lesson)
      const aTeachers = mainTeacherData.map(v => ({
        aType: 1,
        aId: v.value || v.id
      }))
      aTeachers.push(...twoTeacherData.map(v => ({
        aType: 2, aId: v.value || v.id
      })))
      const param = {
        aMerchantId: this.aFirmId,
        aMemo: memo,
        aRoomId: classroom,
        aClassId: classes,
        aCourseId: '2256352a614105ff4e71738da580dd84', // lesson,
        aColor: color,
        aDate: new Date(date).getTime() / 1000,
        aTimeId: time,
        aTeachers,
        aId: this.selectId || ''
      }
      return param
    },

    create() {
      if (this.ifRequesting) return
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        this.ifRequesting = true
        const { code } = await this.$api[this.isAdd ? 'courseCreateSchedule' : 'courseModifyeSchedule'](this.createParam())
        this.ifRequesting = false
        if (code === 0) {
          this.__notify('提示', `${this.isAdd ? '添加成功' : '修改成功'}`)
          this.routerPush('lesson_schedule')
          this.$router.push({ name: 'lesson_schedule' })
        }
      })
    },

    async getLesson() {
      const { code, data } = await this.$api.supplyGetMines({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.lessonData = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async getClassroom() {
      const { code, data } = await this.$api.courseGetRooms({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.classroomData = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async getClasses() {
      const { code, data } = await this.$api.courseGetClasses({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.classesData = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async getTime() {
      const { code, data } = await this.$api.courseGetClassTimes({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.timeData = data.list.map(v => ({
          value: v.id,
          label: `${v.begin_hour}:${v.begin_minute} - ${v.end_hour}:${v.end_minute}`
        }))
      }
    },

    cancel() {
      if (this.ifRequesting) return false
      this.__messageBox({
        title: '你确认要删除该课程吗？',
        successCallback: async () => {
          this.ifRequesting = true
          const { code } = await this.$api.courseDeleteSchedule({ aId: this.selectId })
          this.ifRequesting = false
          this.routerPush('lesson_schedule')
          this.$router.push({ name: 'lesson_schedule' })
          return code
        }
      })
    }
  }
}
</script>

<style lang='less'>
.m-lesson_scheduleDetail {
  &_form {
    .list {
      display: flex;
      flex-wrap: wrap;
      li {
        margin-right: 30px;
        // width: 100px;
      }
    }
    .el-select, .el-input {
      width: 100%;
    }
  }
}
</style>